import React, { Component, createRef } from 'react'
import propTypes from 'prop-types' //组件传值类型校验

export default class Header extends Component {
  state = {
    value: '',
  }
  txtRef = createRef()
  onChange = (e) => {
    // console.log(e.target.value)
    this.setState({ value: e.target.value })
  }
  onKeyDown = (e) => {
    if (e.keyCode === 13) {
      if (this.state.value.trim() === '') {
        alert('请输入内容')
        this.txtRef.current.focus()
        return
      }

      this.props.addContent(this.state.value)
      this.setState({ value: '' })
    }
    return
  }
  render() {
    const { addContent } = this.props
    return (
      <div>
        <header className="header">
          <h1>todos</h1>

          <input
            className="new-todo"
            placeholder="What needs to be done?"
            autoFocus
            onChange={this.onChange}
            value={this.state.value}
            onKeyDown={this.onKeyDown}
            ref={this.txtRef}
          />
        </header>
      </div>
    )
  }
}
Header.propTypes = {
  addContent: propTypes.func,
}
